package com.fcy.musicplayer.repository

import com.fcy.musicplayer.db.entity.Album
import com.fcy.musicplayer.network.MusicService
import com.fcy.musicplayer.network.tpbean.HotPlaylist
import com.fcy.musicplayer.util.LiveDataManager
import com.fcy.musicplayer.util.LoggerUtil
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * 实现 网络请求封装
 */
class Remoter private constructor() {
    private val retrofit: Retrofit
    private val musicService: MusicService
    private var lastBefore: String = "1500706702351"

    init {
        val client = OkHttpClient
            .Builder()
            .addInterceptor(DefaultInterceptor())
            .callTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .build()
        retrofit = Retrofit.Builder()
            .client(client)
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
        musicService = retrofit.create(MusicService::class.java)
    }

    companion object {
        private const val BASE_URL = "http://192.168.1.102:3000"

        @JvmStatic
        private val INSTANCE: Remoter by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
            Remoter()
        }

        /**
         * 得到热放歌单
         */
        fun getHotPlaylist(callback: Callback<HotPlaylist>? = null) {
            INSTANCE.getHotPlaylist(callback)
        }
    }

    fun getHotPlaylist(callback: Callback<HotPlaylist>? = null) {
        val hotPlaylist = musicService.getHotPlaylist(lastBefore, 6)
        callback?.apply {
            hotPlaylist.enqueue(this)
        } ?: hotPlaylist.enqueue(object : Callback<HotPlaylist> {
            override fun onResponse(
                call: Call<HotPlaylist>,
                response: retrofit2.Response<HotPlaylist>
            ) {
                val playlists = response.body()?.playlists ?: return
                val map = playlists.map {
                    Album(
                        it.id.toString(), it.name, it.coverImgUrl,
                        it.playCount.toString(), listOf()
                    )
                }
                LiveDataManager.with<List<Album>>("album").value = map
            }

            override fun onFailure(call: Call<HotPlaylist>, t: Throwable) {
            }

        })

    }

    private class DefaultInterceptor : Interceptor {
        override fun intercept(chain: Interceptor.Chain): Response {
            LoggerUtil.d(chain.request().url())
            return chain.proceed(chain.request())
        }
    }

}
